package com.lagou.web;


import com.lagou.domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginCheckFilter implements Filter {

    private String encode = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //类型向下转型
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        request.setCharacterEncoding(encode);
        response.setContentType("text/html;charset=utf-8");

        //2.判断用户是否为登录状态
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        System.out.println(user);
        boolean flag = (user!=null);
        System.out.println(flag);
        if(user != null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            response.getWriter().println("你还未登录，请先登录！");
        }
    }

    @Override
    public void destroy() {

    }
}
